<template>
	<el-form ref="loginform" :model="form" :rules="rules" label-width="65px">
		<h2>登录页面</h2>
		<el-form-item label="用户名" prop="username">
			<el-input v-model="form.username" placeholder="账号" suffix-icon="el-icon-user"></el-input>
		</el-form-item>
		<el-form-item label="密码" prop="password">
			<el-input v-model="form.password" placeholder="密码" type="password" show-password suffix-icon="el-icon-lock">
			</el-input>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="login">登录</el-button>
			<el-button @click="resetForm">取消</el-button>
		</el-form-item>
	</el-form>
</template>
<script>
	export default {
		data() {
			return {
				form: {
					username: 'admin',
					password: '123456'
				},
				rules: {
					username: [{
							required: true,
							message: '请输入账号',
							trigger: 'blur'
						},
						{
							min: 2,
							max: 6,
							message: '长度在 2 到 6 个字符',
							trigger: 'blur'
						}
					],
					password: [{
							required: true,
							message: '请输入密码',
							trigger: 'blur'
						},
						{
							min: 6,
							max: 15,
							message: '长度在6个字符',
							trigger: 'blur'
						}
					]
				}
			}
		},
		methods: {
		login() {
			// 先验证form表单是否满足验证规则，如果满足则调其中的方法
			// function(valid){.....} -->  (valid)=>{....}
			this.$refs['loginform'].validate(async (valid) => {
				if (valid) {
					//alert(this.form.username + "  " + this.form.password);
					// 获取用户名和密码 调用后端接口，进行登录验证 --axios
					var param = new URLSearchParams();
					param.append('username',this.form.username);
					param.append('password',this.form.password);
					var res = await this.$http.post('login',param);
					// console.log(res)
					// 处理账号或密码有误问题
					if(res.data.code==400){
						this.$message.error(res.data.msg);
						return;
					}
					if(res.data.code==200){
						this.$message.success(res.data.msg);
						// 登录成功后，把登录后返回的token放入到sessionStorage中便于验证登录效果
						window.sessionStorage.setItem('token',res.data.data.token);
						// console.log(res.data.data.token)
						// console.log(res.data.data.id)
						// 把当前用户表中rid的编号放入sessionStrorage对象中
						window.sessionStorage.setItem('rid',res.data.data.rid)
						// 如果登录成功，则进入主页面
						this.$router.push('/welcome')
					}
				} else {
					this.$message.error(res.data.msg)
					return;
				}
			});
		},
		resetForm() {
			this.$refs['loginform'].resetFields();
		}
		}
	}
</script>

<style scoped="scoped">
	.el-form {
		/* border:1px solid red; */
		width: 350px;
		margin: 150px auto;
		padding: 30px 50px;
		border-radius: 10px;
		box-shadow: 0 8px 16px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
	}

	h2 {
		text-align: center;
	}
</style>